package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.example.fileupload.entity.FileInfo;
import com.example.fileupload.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/admin/upload")
public class UploadController extends BaseApiController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
    
    @Autowired
    private FileService fileService;
    
    /**
     * 视频文件上传接口
     * 按照前端upload.vue页面的要求格式返回数据
     */
    @PostMapping("/uploadVidoe")
    public ResponseEntity<Map<String, Object>> uploadVidoe(@RequestParam("file") MultipartFile file) {
        logger.info("接收到视频文件上传请求");
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (file == null || file.isEmpty()) {
                logger.error("上传的视频文件为空");
                response.put("resCode", "400");
                response.put("message", "视频文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            logger.info("视频文件名: {}", file.getOriginalFilename());
            
            // 调用FileService保存文件
            FileInfo savedFile = fileService.saveFile(file);
            
            logger.info("视频文件上传成功，文件ID: {}", savedFile.getId());
            
            // 按照前端期望的格式返回数据
            response.put("resCode", "200");
            response.put("newVidoeName", savedFile.getFileName());
            response.put("VideoUrl", savedFile.getFilePath());
            response.put("message", "视频上传成功");
            
            return ResponseEntity.ok(response);
        } catch (MultipartException e) {
            logger.error("视频文件上传格式错误: {}", e.getMessage());
            response.put("resCode", "400");
            response.put("message", "请求必须是multipart/form-data格式");
            return ResponseEntity.badRequest().body(response);
        } catch (IOException e) {
            logger.error("视频文件上传失败", e);
            response.put("resCode", "500");
            response.put("message", "系统内部错误: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        } catch (Exception e) {
            logger.error("视频文件上传过程中发生未知错误", e);
            response.put("resCode", "500");
            response.put("message", "系统内部错误: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}